package com.xiaoxing.paimai.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.jess.arms.base.BaseLazyFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.paimai.R;
import com.xiaoxing.paimai.di.component.DaggerJieChuJiLuComponent;
import com.xiaoxing.paimai.di.module.JieChuJiLuModule;
import com.xiaoxing.paimai.mvp.contract.JieChuJiLuContract;
import com.xiaoxing.paimai.mvp.presenter.JieChuJiLuPresenter;
import com.xiaoxing.paimai.mvp.ui.adapter.JieChuJiLuAdapter;
import com.xiaoxing.paimai.mvp.ui.entity.JieChuJiLu;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.DateTimePicker;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class JieChuJiLuFragment extends BaseLazyFragment<JieChuJiLuPresenter> implements JieChuJiLuContract.View {

    @BindView(R.id.et_start)
    TextView etStart;
    @BindView(R.id.et_end)
    TextView etEnd;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.tv_no_data)
    TextView tvNoData;

    private RecyclerView recyclerView;

    private List<JieChuJiLu> mItems = new ArrayList<>();
    private List<JieChuJiLu> mJieChuJiLuList = new ArrayList<>();
    private MyHandler mMyHandler;
    private JieChuJiLuAdapter mAdapter;


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMyHandler != null) {
            mMyHandler = null;
        }

    }

    public static JieChuJiLuFragment newInstance() {
        JieChuJiLuFragment fragment = new JieChuJiLuFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerJieChuJiLuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .jieChuJiLuModule(new JieChuJiLuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jie_chu_ji_lu, container, false);
        initRecyclerView(view);
        return view;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        title.setText("借出记录");
        toolbar.setNavigationIcon(null);
        mMyHandler = new MyHandler();


    }

    private String getSpPort() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT);
    }

    private String getSpIP() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP);
    }

    private void getJieChuJiLuData() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // WSDL文档的URL，192.168.17.156为PC的ID地址
                String url = "http://" + getSpIP() + ":" + getSpPort()
                        + "/ws/ContainerService.asmx";
                String nameSpace = "http://tempuri.org/";
                // 定义调用的WebService方法名
                String methodName = "outstoreListForAndroid";
                String soapAction = nameSpace + methodName;
                try {

                    /****************** 调用webService ***********************/

                    // 设置连接参数
                    SoapObject request = new SoapObject(nameSpace, methodName);
                    String startTime = etStart.getText().toString();
                    String endTime = etEnd.getText().toString();
                    String uname = mSharedPreferencesHelper.getString(BaseConstants.USERNAME);
                    request.addProperty("uname", uname);
                    request.addProperty("StartTime", startTime);
                    request.addProperty("EndTime", endTime);
                    request.addProperty("storeType", "1");
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
                    // V1.1）;

                    // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
                    // 不指定rpc方式则用true否则要用false
                    envelope.dotNet = true;

                    // envelope.setOutputSoapObject(request);//设置请求参数
                    envelope.bodyOut = request; // enveloper.bodyOut=request 与
                    // envelope.setOutputSoapObject(request)
                    // 效果相同。
                    // step4 创建HttpTransportSE对象
                    HttpTransportSE ht = new HttpTransportSE(url);
                    // step5 调用WebService
                    ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
                    if (envelope.getResponse() != null) {
                        Object response = (Object) envelope.getResponse();
                        // if ("1".equals(response.toString())) {
                        String t = response.toString();

                        if (!TextUtils.isEmpty(t) && !t.equals("anyType{}")) {
                            mItems.clear();
                            String[] arys = t.split("@");
                            for (String item : arys) {
                                try {
                                    String[] aary = item.split("#");
                                    JieChuJiLu jieChuJiLu = new JieChuJiLu();
                                    jieChuJiLu.setXingHao(aary[0]);
                                    jieChuJiLu.setJianShu(aary[1]);
                                    jieChuJiLu.setShiJian(aary[2]);
                                    mItems.add(jieChuJiLu);
                                } catch (Exception e) {
                                    continue;
                                }
                            }
                            mMyHandler.sendEmptyMessage(0);
                        } else {

                            mItems.clear();
                            mMyHandler.sendEmptyMessage(1);
                        }

                    }
                    /****************** 调用webService结束 ***********************/

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                onYearMonthDayTimePicker(etStart);
                break;
            case R.id.et_end:
                onYearMonthDayTimePicker(etEnd);
                break;
            case R.id.btn_search:
                getJieChuJiLuData();
                break;
        }
    }


    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            LoadingDialogUtil.dismissDialog();
            switch (msg.what) {
                case 0:
                    tvNoData.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    mJieChuJiLuList.clear();
                    mJieChuJiLuList.addAll(mItems);
                    mAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    tvNoData.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                    mJieChuJiLuList.clear();
                    mJieChuJiLuList.addAll(mItems);
                    mAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }


    }

    private void initRecyclerView(View view) {
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mAdapter = new JieChuJiLuAdapter(getActivity(), mJieChuJiLuList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void loadData() {
        getJieChuJiLuData();
    }

    public void onYearMonthDayTimePicker(TextView view) {

        DateTimePicker picker = new DateTimePicker(getActivity(), DateTimePicker.HOUR_24);

        Calendar now = Calendar.getInstance();

        picker.setCancelText("取消");
        picker.setSubmitText("确定");
        picker.setActionButtonTop(true);
        picker.setDateRangeStart(1900, 1, 1);
        picker.setDateRangeEnd(2500, 12, 31);
        picker.setSelectedItem(now.get(Calendar.YEAR), (now.get(Calendar.MONTH) + 1), now.get(Calendar.DAY_OF_MONTH), now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE));
        picker.setTimeRangeStart(0, 0);
        picker.setTimeRangeEnd(23, 59);
        picker.setCanLinkage(false);
        picker.setTitleText("请选择");
//        picker.setStepMinute(5);
        picker.setWeightEnable(true);
        picker.setWheelModeEnable(true);
        LineConfig config = new LineConfig();
        config.setColor(Color.BLACK);//线颜色
        config.setAlpha(120);//线透明度
        config.setVisible(true);//线不显示 默认显示
        picker.setLineConfig(config);
        picker.setLabel("年", "月", "日", "时", "分");
        picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() {
            @Override
            public void onDateTimePicked(String year, String month, String day, String hour, String minute) {
//                ArmsUtils.snackbarText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
                view.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
            }
        });
        picker.show();

    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }


}
